﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using calculation.Models;

namespace calculation.Controllers
{
    public class MaterialController : Controller
    {
        private DataManager _dataManager;
        public MaterialController(DataManager dataManager)
        {
            _dataManager = dataManager;
        }

        public ActionResult List()
        {
            ViewData["Name"] = "Справочник материалов";
            ViewData["Materials"] = _dataManager.Materials.GetMaterials();

            return View();

        }

        public ActionResult Material(int id)
        {
            ViewData.Model = _dataManager.Materials.GetMaterials(id);
            return View();
        }
        public ActionResult Delete(int id)
        {
            _dataManager.Materials.DeleteMaterial(id);

            return RedirectToAction("List");
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Add()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Add(string name, string typeMaterial, int amount)
        {
            if (name.Length <= 3)
                ModelState.AddModelError("Name", "Name ....");
            if (typeMaterial.Length < 4)
                ModelState.AddModelError("Type_detal", "Name ....");

            if (ModelState.IsValid)
            {
                _dataManager.Materials.CreateMaterial(name, typeMaterial, amount);
                return RedirectToAction("List");
            }
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Edit(int id)
        {
            Material m = _dataManager.Materials.GetMaterials(id);
            ViewData.Model = m;

            SetEditLists(m);
            return View();
        }

        private void SetEditLists(Material m)
        {
            ViewData["Producers"] = new SelectList(_dataManager.Producers.GetProducers(),
                   "ProducerId", "FirmName",m.ProducerId);
           

        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, Material m)
        {
            if (m.Name.Length <= 3)
                ModelState.AddModelError("Name", "Name ....");
            if (m.TypeMaterial.Length < 4)
                ModelState.AddModelError("Type_detal", "Name ....");

            if (ModelState.IsValid)
            {
                m.MaterialId = id;
                _dataManager.Materials.UpdateMaterial(m);
                return RedirectToAction("List");

            }
            SetEditLists(m);
            return View();


        }
    }
}